#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""  
@Project : PythonProject
@File : redis_val.py
@Author : donc
@Time : 2025/5/29 18:08  
@脚本说明 : Redis弱口令检测模块
"""
import threading
from redis import Redis
from queue import Queue


def val_redis(host, port, password_file):
    """
    Redis弱口令检测主函数
    返回格式: {"host": [], "port": [], "password": []}
    """
    # 读取密码字典
    try:
        passwords = password_file.getvalue().decode().splitlines()
    except Exception as e:
        return {"error": f"字典文件读取失败: {str(e)}"}

    # 创建线程安全队列
    result_queue = Queue()
    threads = []

    # 创建并启动线程
    for password in passwords:
        t = threading.Thread(
            target=try_redis_connection,
            args=(host, int(port), password.strip(), result_queue)
        )
        t.start()
        threads.append(t)

        # 等待所有线程完成
        for t in threads:
            t.join()

        # 收集结果
        results = {
            "host": [],
            "port": [],
            "password": []
        }

    while not result_queue.empty():
        result = result_queue.get()
        results["host"].append(result["host"])
        results["port"].append(result["port"])
        results["password"].append(result["password"])

    return results


def try_redis_connection(host, port, password, result_queue):
    """尝试连接Redis并验证密码"""
    try:
        redis_cli = Redis(
            host=host,
            port=port,
            password=password,
            db=0,  # 默认数据库
            socket_connect_timeout=3,
            socket_timeout=3
        )

        # 简单测试连接
        redis_cli.ping()

        # 连接成功，保存结果
        result_queue.put({
            "host": host,
            "port": port,
            "password": password
        })

        # 关闭连接
        redis_cli.close()

    except Exception as e:
        # 连接失败，忽略错误
        pass